package com.eshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eshop.mapper.UserMapper;
import com.eshop.pojo.Role;
import com.eshop.pojo.User;
import com.eshop.service.MenuService;
import com.eshop.service.RoleService;
import com.eshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2024-01-17 11:35:24
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(User::getUsername,username);
        queryWrapper.eq(User::getEnabled,1);
        User user = getOne(queryWrapper);
        if(user==null){
            throw new UsernameNotFoundException("账号或密码错误");
        }
        Role role = roleService.getRoleByUid(user.getId());
        user.setAuthorities(AuthorityUtils.createAuthorityList(role.getName()));
        user.setMenus(menuService.getMenuListByRid(role.getId()));
        return user;
    }
}

